import base
print('Step 1: Install basic packages and do basic configure')

'''
COPY CONFIG
'''
# base.run('cp -a -f ./etc/* /etc')
base.run('cp -r -f ./etc/* /etc')

'''
CHECK NETWORK
'''
import sys
if not base.is_network_accessible():
    print('Unable to update packs database. Please check your network connection.')
    sys.exit()


'''
SELECT KERNEL
'''
# Show
KERNELS = ('linux-lts', 'linux', 'linux-hardened', 'linux-zen', 'linux-ck-generic-v2', '(input manually)')

print()
base.run("/lib/ld-linux-x86-64.so.2 --help | grep supported")
print('These are kernels officially supported.')
index = 0
for kernel in KERNELS:
    index += 1
    print(f'\t{index}: {kernel}')
print()
print('Input the relevant number(s) and press Enter to install (separated by space(s)) (default:1):', end='')
opt_strs = input().split()

# Check Input
kernels_selected = []
for opt_str in opt_strs:
    if opt_str.isdigit():
        opt = int(opt_str)-1
        if opt in range(0, len(KERNELS)-1):
            # Select
            kernels_selected.append(KERNELS[opt])
        elif opt == (len(KERNELS)-1):
            # Input
            print('Input the kernel\'s package name (linux-*):', end='')
            kernel = input()
            if kernel.startswith('linux') and base.run(f'pacman -Si {kernel}') == 0:
                kernels_selected.append(kernel)
if len(kernels_selected) == 0:
    kernels_selected.append(KERNELS[0])

print('\tSelected kernel: ', kernels_selected)
print('Start Installation? [Y/n]', end='')
if not base.input_yes_or_no(True):
    print("Installation canceled.")
    sys.exit()


'''
INSTALLATION
'''
print('Installation started.')

pkgs_kernel = ''
for kernel in kernels_selected:
    pkgs_kernel += f'{kernel} {kernel}-headers '
pkgs_base = 'base base-devel multilib-devel dkms archlinuxcn-keyring'
# pkgs_firmware = 'linux-firmware wd719x-firmware aic94xx-firmware rock-dkms-firmware-bin'
pkgs_firmware = 'linux-firmware wd719x-firmware aic94xx-firmware'
pkgs_bootloader = 'intel-ucode amd-ucode'
pkgs_filesystem = 'e2fsprogs dosfstools ntfs-3g btrfs-progs'
pkgs_network = 'net-tools networkmanager iwd'
pkgs_software = 'vi vim neovim man-db man-pages fish git python'
pkgs_tools = 'gptfdisk parted'

_pkgs_set = [pkgs_kernel, pkgs_base, pkgs_firmware, \
    pkgs_bootloader, pkgs_filesystem, pkgs_network, pkgs_software, \
    pkgs_tools]
pkgs = ''
for _pkg in _pkgs_set:
    pkgs += _pkg
    pkgs += ' '

# Configure mkinitcpio
for kernel in kernels_selected:
    # base.run("mkdir /mnt/etc && mkdir /mnt/etc/mkinitcpio.d")
    base.run("mkdir -p /mnt/etc/mkinitcpio.d")
    initfile_path=f"/mnt/etc/mkinitcpio.d/{kernel}.preset"
    initfile_content = \
    f""" ALL_config=\"/etc/mkinitcpio.conf\"
    ALL_kver=\"/boot/vmlinuz-{kernel}\"
    PRESETS=('default')
    default_image=\"/boot/initramfs-{kernel}.img\"
    default_options=\"-S autodetect\" """

    initfile = open(initfile_path, mode='w')
    initfile.write(initfile_content)
    initfile.close()

# Copy cache
print("Coping cache...")
base.run("mkdir -p /mnt/var/cache/pacman/pkg")
base.run('cp -r -f ./packs-cache/* /mnt/var/cache/pacman/pkg/')


# Install
if base.run("pacstrap /mnt " + pkgs) == 0:
    base.run("genfstab -t PARTUUID /mnt > /mnt/etc/fstab")

    # After_install
    # base.run("cp -a -f ./etc /mnt")
    base.run("cp -r -f ./etc /mnt")
    # base.run("mkdir -p /mnt/script && cp -a -f . /mnt/script")
    base.run("mkdir -p /mnt/script && cp -r -f . /mnt/script")

    print()
    print('\tNow use \'arch-chroot /mnt\' and \'cd /script\' to go to the next step.')
    print()
